<template>
  <a-spin class="operatePutIn new-box" tip="加载中..." :spinning="isLoading">
    <div class="new-button-box">
      <a-button type="primary" icon="plus-square" @click="applyDjMoney" style="background:#1d6fe9"> 申请抖加费用</a-button>
      <a-button type="primary" icon="account-book" @click="applyReimbursementMoney" class="green-btn">申请报销费用</a-button>
    </div>
    <!-- 筛选 -->
    <div :class="['new-box-filter df', isShowMore ? 'new-box-show' : '']">
      <div class="new-box-filter-left">
        <div class="df flex-ali-center">
          <div class="margin-right-16">
            <span>大区：</span>
            <a-select
              class="wid-160"
              showSearch
              :defaultActiveFirstOption="false"
              :filterOption="false"
              @search="getAllAreaFun($event)"
              @change="changeLocation"
              v-model="search.areaId"
              placeholder="请选择大区"
            >
              <a-select-option :value="null">全部</a-select-option>
              <a-select-option v-for="item in allArea" :key="item.configId" :value="item.configId">{{ item.name }}</a-select-option>
            </a-select>
          </div>
          <div class="margin-right-16">
            <span>请款审核状态：</span>
            <a-select class="wid-160" placeholder="请选择请款审核状态" v-model="search.status" @change="handleByQueryCond">
              <a-select-option v-for="item in auditStatuList" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
            </a-select>
          </div>
          <div class="margin-right-16">
            <span>报销情况：</span>
            <a-select class="wid-160" placeholder="请选择状态" v-model="search.reimbursementStatus" @change="handleByQueryCond">
              <a-select-option v-for="item in reimbursementStatuList" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
            </a-select>
          </div>
          <div class="margin-right-16">
            <span>申请请款时间：</span>
            <a-range-picker class="wid-240" @change="handleByQueryCond" v-model="search.selectDateApply" />
          </div>
          <a-dropdown v-if="!isShowMore" class="wid-70 flex-shrink-0">
            <a class="ant-dropdown-link" @click="moreSearch"> 更多条件<a-icon type="down" /> </a>
          </a-dropdown>
        </div>
        <div class="df">
          <div class="margin-top-10" v-show="isShowMore">
            <span>近期投放时间：</span>
            <a-range-picker class="wid-240" @change="handleByQueryCond" v-model="search.selectDatePutIn" />
          </div>
        </div>
      </div>

      <div class="new-box-filter-right flex-shrink-0">
        <a-dropdown v-if="isShowMore" class="wid-70 flex-shrink-0" style="margin-right:10px;">
          <a class="ant-dropdown-link" @click="moreSearch"> 收起<a-icon type="up" /> </a>
        </a-dropdown>
        <a-button type="primary" @click="handleByQueryCond" class="gray-btn">查询</a-button>
        <a-button @click="resetSearch" class="border-radious-2">重置</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <!-- todo “可投放、已投放”金额在请款未通过是为黑色 -->
    <div class="main-body self-time-line">
      <a-table :columns="tableColumns" class="scrollstyle" :pagination="false" :data-source="dataList" :scroll="{ x: 1200, y: tableHeight }" rowKey="id">
        <!-- 已投放金额 -->
        <template slot="usedMoney" slot-scope="text, record">
          <span :class="{ 'green-text': record.availableMoney > 0 && record.status !== 0, 'red-text': record.availableMoney === 0 && record.status !== 0 }">{{
            record.usedMoney ? (record.usedMoney / 100).toFixed(2) : 0
          }}</span>
        </template>
        <!-- 可投放余额 -->
        <template slot="availableMoney" slot-scope="text, record">
          <span :class="{ 'green-text': record.availableMoney > 0 && record.status !== 0, 'red-text': record.availableMoney === 0 && record.status !== 0 }">{{
            record.availableMoney ? (record.availableMoney / 100).toFixed(2) : 0
          }}</span>
        </template>
        <!-- 报销情况 -->
        <template slot="reimbursementStatusStr" slot-scope="text, record">
          <div>
            <p>{{ record.reimbursementStatusStr || '无' }}</p>
            <p>已报销：¥ {{ record.reimbursementMoney ? (record.reimbursementMoney / 100).toFixed(2) : '0' }}</p>
          </div>
        </template>
        <!-- 请款审核情况 -->
        <template slot="statusStr" slot-scope="text, record">
          <div>
            <!-- 0审核中 1审核同过 2驳回 -->
            <p :class="['audit-status', record.status === 1 ? 'audit-pass' : record.status === 2 ? 'audit-reject' : '']">{{ record.statusStr }}</p>
            <a-tooltip>
              <template slot="title">
                {{ record.rejectReason || '无' }}
              </template>
              <p v-if="record.status === 2 && record.rejectReason" class="reject-reason">理由：{{ record.rejectReason || '无' }}</p>
            </a-tooltip>
          </div>
        </template>

        <!-- 操作按钮 -->
        <template slot="action" slot-scope="text, record">
          <!-- 审核状态 0审核中 1审核同过 2驳回 -->
          <!-- status审核通过 && 可用余额>0 ==== 投放，详情，记录修正，导入投放 -->
          <!-- status审核通过 && 可用余额=0 ==== 详情，记录修正 -->
          <!-- status审核驳回 ==== 编辑申请、删除 -->
          <!-- status审核中 ==== 无 -->
          <!-- 投放 -->
          <a-button type="link" href="javascript:;" size="small" v-if="record.status === 1 && record.availableMoney > 0" @click="putInAction(record)">投放</a-button>
          <!-- 详情 -->
          <a-button type="link" href="javascript:;" size="small" v-if="record.status === 1 && record.availableMoney >= 0" @click="detaiAction(record)">详情</a-button>
          <!-- 记录修正 -->
          <a-button type="link" href="javascript:;" size="small" v-if="record.status === 1 && record.availableMoney >= 0" @click="modifyAction(record)">记录修正</a-button>
          <!-- 导入投放 -->
          <a-button type="link" href="javascript:;" size="small" v-if="record.status === 1 && record.availableMoney > 0" @click="importAction(record)">导入投放</a-button>
          <!-- 编辑申请 -->
          <a-button type="link" href="javascript:;" v-if="record.status === 2" size="small" @click="editApplyAction(record)">编辑申请</a-button>
          <!-- 删除 -->
          <a-button type="link" href="javascript:;" v-if="record.status === 2" class="red-text" size="small" @click="deleteAction(record)">删除</a-button>
          <span v-if="record.status === 0" style="color:#999;">无操作</span>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container new-paging-container">
      <a-pagination
        :pageSize="search.pageSize"
        v-model="search.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
    <!-- 申请抖加费用 -->
    <apply-money
      v-model="isShowApplyMoney"
      :getAreaList="allArea"
      :detailInfo="applyMoneyDetail"
      :type="applyMoneyType"
      :personInfo="personInfo"
      @callback="callbackFn"
      @onCancel="handleCancel"
    ></apply-money>
    <!-- 详情或记录修正 -->
    <apply-detail-modify v-model="isShowApplyModify" :configInfo="configInfo" :detailInfo="detailInfo" @callback="callbackFn" :getInfo="postItemInfo" :type="modifyType"></apply-detail-modify>
    <!-- 投放 -->
    <apply-puton v-model="isShowApplyPuton" :getInfo="postItemInfo" :configInfo="configInfo" :douApplyId="douApplyId" @callback="callbackFn"></apply-puton>
    <!-- 导入导出 -->
    <export-in :douApplyId="douApplyId" v-model="isShowExportIn" @callback="callbackFn"></export-in>
    <!-- 申请报销 -->
    <apply-reimbursement
      v-model="isShowApplyReimbursement"
      :getAreaList="allArea"
      :getInfo="applyMoneyDetail"
      :personInfo="personInfo"
      @callback="callbackFn"
      @onCancel="handleCancel"
    ></apply-reimbursement>
  </a-spin>
</template>

<script>
import { getCommonApiSearch, getUserInfoUrl } from '@/service'
import { djListUrl, djDetailUrl, djRejectedDeleteUrl, djUpdateDetailUrl, areaAllListUrl } from '@/service/djService'
import upload from '@/components/upload/upload'
import applyMoney from './component/applyMoney'
import applyReimbursement from './component/applyReimbursement'
import applyDetailModify from './component/applyDetailModify'
import applyPuton from './component/applyPuton'
import exportIn from './component/exportIn'
import moment from 'moment'
import debounce from 'lodash/debounce'
import { douJiaColumn } from './column'
import '@/assets/style/newStyle.scss'
export default {
  name: 'operatePutIn',
  data() {
    // 节流
    this.getAllStation = debounce(this.getAllStation, 800)
    // this.getAllAreaFun = debounce(this.getAllAreaFun, 800)
    return {
      moment,
      pagination: {
        total: 0
      },
      // 全部站点
      allStation: [],
      // table list
      dataList: [],
      // table数据查询条件
      search: {
        areaId: '',
        reimbursementStatus: '',
        status: '',
        selectDcomputedateApply: [],
        selectDatePutIn: [],
        pageIndex: 1,
        pageSize: 10
      },
      tableColumns: douJiaColumn.operatePutIn,
      // 申请抖加费用显示隐藏
      isShowApplyMoney: false,
      // 申请报销显示隐藏
      isShowApplyReimbursement: false,
      // 详情/记录修正显示隐藏
      isShowApplyModify: false,
      // 登录人员信息
      personInfo: {},
      //  申请抖加费用详情
      detailInfo: {},
      // 全局loading
      isLoading: false,
      // 投放显示隐藏
      isShowApplyPuton: false,
      // 导入显示隐藏
      isShowExportIn: false,
      // 投放弹窗展示信息
      postItemInfo: {},
      // 详情/记录修正
      modifyType: 1,
      // 抖加申请类型
      applyMoneyType: 0,
      // 抖加申请详情
      applyMoneyDetail: {},
      // item对应id
      douApplyId: 0,
      // 大区list
      allArea: [],
      isShowMore: false,
      configInfo: {}
    }
  },

  components: {
    upload,
    applyMoney,
    applyReimbursement,
    applyDetailModify,
    exportIn,
    applyPuton
  },

  computed: {
    // 审核状态
    auditStatuList() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '审核中',
          value: 0
        },
        {
          name: '审核通过',
          value: 1
        },
        {
          name: '驳回',
          value: 2
        }
      ]
    },
    // 报销情况
    reimbursementStatuList() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '未报销',
          value: 0
        },
        {
          name: '部分报销',
          value: 1
        },
        {
          name: '全部报销',
          value: 2
        }
      ]
    }
  },

  methods: {
    moreSearch(e) {
      e.preventDefault()
      this.isShowMore = !this.isShowMore
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.search.pageIndex = 1
      this.setPath(this.getParams())
      this.query()
    },
    // 重置
    resetSearch() {
      this.search = {
        areaId: '',
        reimbursementStatus: '',
        status: '',
        selectDcomputedateApply: [],
        selectDatePutIn: [],
        pageIndex: 1,
        pageSize: 10
      }
      this.setPath(this.getParams())
      this.query()
    },
    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.search.pageIndex = num
      this.setPath(this.getParams())
      this.query()
    },

    getAllStation(e) {
      getCommonApiSearch({ keywords: e }).then((res) => {
        console.log(res)
        this.allStation = res
      })
    },

    callbackFn() {
      this.search.pageIndex = 1
      this.query()
    },
    // 选择了站点
    changeLocation() {
      this.search.pageIndex = 1
      this.initQuery()
    },

    // 拿参数
    getParams() {
      const { areaId, reimbursementStatus, status, selectDateApply = [], selectDatePutIn = [], pageIndex, pageSize } = this.search
      return {
        pageIndex,
        pageSize,
        areaId,
        reimbursementStatus,
        status,
        startDate: selectDatePutIn[0] ? moment(selectDatePutIn[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endDate: selectDatePutIn[1] ? moment(selectDatePutIn[1]).format('YYYY-MM-DD 23:59:59') : undefined,
        applyStartDate: selectDateApply[0] ? moment(selectDateApply[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        applyEndDate: selectDateApply[1] ? moment(selectDateApply[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, areaId, reimbursementStatus, status, startDate, endDate, applyStartDate, applyEndDate } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          pageIndex: isNaN(pageIndex) ? 1 : +pageIndex,
          pageSize: 10,
          areaId: isNaN(areaId) ? null : +areaId,
          status: status || '',
          reimbursementStatus: reimbursementStatus || '',
          selectDatePutIn: startDate && endDate ? [startDate, endDate] : [],
          selectDateApply: applyStartDate && applyEndDate ? [applyStartDate, applyEndDate] : []
        }
      }
    },
    // 初始化
    initQuery() {
      // this.search.pageIndex = 1
      this.search.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 获取列表
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      djListUrl(this.getParams())
        .then((rs) => {
          console.log(rs)
          this.dataList = Object.freeze(rs.applyListData) || []
          this.pagination.total = rs.total || 0
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key] || origin[key] === 0) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    // 详情
    detaiAction(row = {}) {
      const { id = '', area = '', money = 0, availableMoney = 0, usedMoney = 0, createTime = '' } = row
      this.postItemInfo = { area, money, availableMoney, usedMoney, createTime }
      this.modifyType = 1
      this.isLoading = true
      this.getDetailInfo(id)
        .then(() => {
          this.isShowApplyModify = true
          this.isLoading = false
        })
        .catch(() => {
          this.$messageSend.error('网络错误')
          this.isLoading = false
        })
    },
    // 投放
    putInAction(row = {}) {
      const { id = '', area = '', money = 0, areaId = 0, availableMoney = 0, usedMoney = 0, createTime = '' } = row
      this.postItemInfo = { area, money, availableMoney, usedMoney, createTime, id }
      this.configInfo = { area, areaId }
      this.douApplyId = id
      this.isShowApplyPuton = true
    },
    // 记录修正
    modifyAction(row = {}) {
      const { id = '', area = '', areaId = 0, money = 0, availableMoney = 0, usedMoney = 0, createTime = '' } = row
      this.postItemInfo = { area, money, availableMoney, usedMoney, createTime }
      this.modifyType = 2
      this.isLoading = true
      this.configInfo = { area, areaId }
      this.getDetailInfo(id)
        .then(() => {
          this.isShowApplyModify = true
          this.isLoading = false
        })
        .catch(() => {
          this.$messageSend.error('网络错误')
          this.isLoading = false
        })
    },
    // 导入投放
    importAction(row = {}) {
      const { id = '' } = row
      this.douApplyId = id
      console.log(this.douApplyId)
      this.isShowExportIn = true
    },
    // 编辑申请
    editApplyAction(row = {}) {
      const { id = '' } = row
      this.getDjApplyMoneyDetail(id).then(() => {
        this.applyMoneyType = 1
        this.isShowApplyMoney = true
      })
    },
    // 获取编辑抖加申请详情
    getDjApplyMoneyDetail(id = '') {
      return new Promise((resolve, reject) => {
        djUpdateDetailUrl({ id }).then((res = {}) => {
          this.applyMoneyDetail = res
          resolve()
        })
      })
    },

    // 删除
    deleteAction(row = {}) {
      const { id = '' } = row
      const { $messageSend, $confirm, query } = this
      $confirm({
        title: '删除',
        content: '确定要删除该条数据吗？',
        onOk: () => {
          // 发送请求
          return djRejectedDeleteUrl({ id })
            .then((res) => {
              query()
              $messageSend.success('操作成功')
            })
            .catch((err) => err)
        }
      })
    },
    // 申请抖加费用
    applyDjMoney(row = {}) {
      const { id = '' } = row
      this.applyMoneyType = 0
      const { name = '', userId = '' } = this.personInfo || {}
      if (name && userId) {
        this.isShowApplyMoney = true
      } else {
        this.getUserInfo(id)
          .then(() => {
            this.isShowApplyMoney = true
          })
          .catch(() => {
            this.$messageSend.error('网络错误')
          })
      }
    },
    // 申请报销费用
    applyReimbursementMoney() {
      const { name = '', userId = '' } = this.personInfo || {}
      if (name && userId) {
        this.isShowApplyReimbursement = true
      } else {
        this.getUserInfo()
          .then(() => {
            this.isShowApplyReimbursement = true
          })
          .catch(() => {
            this.$messageSend.error('网络错误')
          })
      }
    },
    handleCancel() {
      this.applyMoneyType = 0
      this.isShowApplyMoney = false
      this.isShowApplyReimbursement = false
    },
    // 获取登录人员公共信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        getUserInfoUrl().then((res = {}) => {
          console.log(res)
          const { name = '', userId = '' } = res
          this.personInfo = { name, userId }
          resolve()
        })
      })
    },
    getDetailInfo(id = '') {
      return new Promise((resolve, reject) => {
        djDetailUrl({ id }).then((res = {}) => {
          console.log(res)
          this.detailInfo = res
          resolve()
        })
      })
    },
    getAllAreaFun() {
      return new Promise((resolve, reject) => {
        this.userLoading = true
        areaAllListUrl()
          .then((res = []) => {
            this.allArea = res
            resolve()
          })
          .catch(() => {
            return reject(new Error('接口出错'))
          })
          .finally(() => {
            this.userLoading = false
          })
      })
    }
  },
  mounted() {
    // 获取所有大区
    this.getUserInfo()
    this.getAllAreaFun()
      .then(() => {
        // this.setSearch()
        this.initQuery()
      })
      // 获取失败依然继续请求列表数据
      .catch((err) => err)
    // 先获取用户信息保存
  },

  filters: {}
}
</script>

<style lang="less" scoped>
/deep/ .ant-btn-sm {
  padding-left: 0;
}
.anchor-review {
  padding: 16px;
}

.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}

p {
  margin-bottom: 5px;
  font-size: 13px;
}
.font-weight-bold {
  font-weight: bold;
  display: inline-block;
}
// .main-body {
//   width: 1920px;
//   overflow-x: scroll;
// }
</style>
